const errorTypes = require('../constants/error-types')
const { resDesign } = require('../utils/dataDesign')
const HTTP_CODE = require('./http-code')

const errorHandler = (error, ctx) => {
  let status, message

  switch (error.message) {
    case errorTypes.ACCOUNT_OR_PASSWORD_IS_REQUIRED:
      status = HTTP_CODE.error // Bad Request
      message = '用户名或者密码不能为空'
      break
    case errorTypes.USER_ALREADY_EXISTS:
      status = 409 // conflict
      message = '账号已经存在'
      break
    case errorTypes.USER_DOES_NOT_EXISTS:
      status = HTTP_CODE.error // 参数错误
      message = '用户名不存在'
      break
    case errorTypes.PASSWORD_IS_INCORRENT:
      status = HTTP_CODE.error // 参数错误
      message = '密码错误'
      break
    case errorTypes.UNAUTHORIZATION:
      status = HTTP_CODE.outOfData // 参数错误
      message = '无效的token'
      break
    case errorTypes.UNPERMISSION:
      status = HTTP_CODE.unpermission // 权限错误
      message = '您不具备操作的权限'
      break
    default:
      status = HTTP_CODE.notFound
      message = '404 - NOT FOUND'
  }

  // ctx.status = status
  ctx.body = resDesign({ code: status, msg: message })
}

module.exports = errorHandler
